package com.wlcorp.forcazamis.dao.storagein.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ibatis.dao.client.DaoException;
import com.wlcorp.forcazamis.dao.storagein.IStorageInDAO;
import com.wlcorp.forcazamis.domain.storagein.StorageIn;

public class StorageInDAOImpl extends HibernateDaoSupport implements
		IStorageInDAO {

	@SuppressWarnings("unchecked")
	public List getStorageInList(final StorageIn storageIn) throws DaoException {
		final StringBuffer queryString = new StringBuffer("select storageIn from StorageIn as storageIn where 1=1 and storageIn.deleteFlag=false");
		if(null != storageIn){
			if(null != storageIn.getSubmiterId() ){
				queryString.append(" and storageIn.submiter.staffId = ").append(storageIn.getSubmiterId());
			}
			if(null != storageIn.getType()){
				queryString.append(" and storageIn.type = ").append(storageIn.getType());
			}
		}
		return getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString.toString());
				if(null != storageIn && null != storageIn.getMinRownum()){
					query.setFirstResult(storageIn.getMinRownum());
					query.setMaxResults(storageIn.getNumPerPage());
				}
				return query.list();
			}
			
		});
	}

	public Long getStorageInCount(StorageIn storageIn) throws DaoException {
		final StringBuffer queryString = new StringBuffer("select count(storageIn) from StorageIn as storageIn where 1=1 and storageIn.deleteFlag=false");
		if(null != storageIn){
			if(null != storageIn.getSubmiterId()){
				queryString.append(" and storageIn.submiter.staffId = ").append(storageIn.getSubmiterId());
			}
			if(null != storageIn.getType()){
				queryString.append(" and storageIn.type = ").append(storageIn.getType());
			}
		}
		return (Long)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString.toString());
				return query.uniqueResult();
			}
			
		});
	}

	public StorageIn getStorageInById(Long storageInId) throws DaoException {
		return (StorageIn)getHibernateTemplate().get(StorageIn.class,storageInId);
	}

	public void deleteStorageIn(StorageIn storageIn) throws DaoException {
		storageIn.setDeleteFlag(true);
		getHibernateTemplate().update(storageIn);
	}

	public void saveStorageIn(StorageIn storageIn) throws DaoException {
		getHibernateTemplate().saveOrUpdate(storageIn);
	}


}
